import server
import threading
import os
import sendmail

def handleClient(conn):
    print("thread name:", threading.currentThread().getName())
    data = conn.recv(1024)
    info = server.parseData(data.decode('utf-8'))
    # recv attach data and write to attach file
    conn.sendall(info['path'].encode("utf-8"))
    attach = conn.recv(info['size'])
    tmpfile = os.path.basename(info['path'])
    print("attach file:", tmpfile)
    with open(tmpfile, "wb") as f:
        f.write(attach)
    # send email 
    if sendmail.send_attach(info['to'], info['head'], tmpfile):
        result = "ok"
    else :
        result = "fail"
    # remove the attach file
    os.remove(tmpfile)
    # insert info to database
    server.updateDBInfo(info, result)
    reponse = "result:"+result
    # send result to client
    conn.sendall(reponse.encode('utf-8'))
    conn.close()

serv_sock = server.createServer(7777)
while True:
    try:
        conn, addr = serv_sock.accept()
        print ("connected with:{0}:{1}".format(addr[0], addr[1]))
        #handleClient(conn)
        # create client handle thread
        t = threading.Thread(target=handleClient, args=(conn, ))
        t.start()
    except KeyboardInterrupt:
        print("email server exit!")
        break

serv_sock.close()
